package com.asimplefox.filter;

import com.alibaba.fastjson.JSON;
import com.asimplefox.serurity.TokenManager;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class AuthFilter extends OncePerRequestFilter {
    private static final SimpleDateFormat DF2 = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒SSS");

    @Autowired
    TokenManager tokenManager;

    @Override
    protected synchronized void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        UserDetails userDetails = tokenManager.getContextUserDetail(request);
        if (userDetails != null && userDetails.isEnabled()) {
            log.debug("user({}) call path:{}", userDetails.getUsername(), request.getRequestURL());
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } else {
            SecurityContextHolder.clearContext();
        }
        synchronized (DF2) {
            String ip = request.getHeader("x-forwarded-for");
            if (ip == null) ip = request.getRemoteAddr();
            ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
            log.debug("[{}]:{}[{}]({})", DF2.format(new Date(System.currentTimeMillis())), ip, request.getMethod()
                    , request.getRequestURL());
            log.debug(JSON.toJSONString(request.getParameterMap()));
        }
        filterChain.doFilter(request, response);
    }
}